<template>
	<view class="auth-page">
		<y-cubar title=" " :bgColor="`rgba(255,255,255,${opacity})`" />
		<view class="auth-page-bg"></view>
		<view class="hand-top">
			<view class="hand-top-left">
				<image class="title" src="/static/car/title.png" mode=""></image>
				<view class="more">
					<text>为了租车安全交易，需认证为车商</text>
				</view>
			</view>
			<image class="bg" src="/static/car/bg.png" mode=""></image>
		</view>
		<view class="form">
			<view class="tabs">
				<uv-tabs :list="tabList" lineColor="#FFC434" :scrollable="false" :inactiveStyle="inactiveStyle"
					:activeStyle="inactiveStyle" lineWidth="78rpx" lineHeight="8rpx" @click="tabChange"></uv-tabs>
			</view>
			<template v-if="queryform.type === 'ENTERPRISE'">
				<view class="form-item">
					<view class="label">
						<text>营业执照照片</text>
					</view>
					<view class="uplaods">
						<view class="upload" @click="handChooseImg('licensePhotos')">
							<image v-if="queryform.licensePhotos" :src="queryform.licensePhotos" mode="aspectFill">
							</image>
							<image v-else src="../../static/zheng.png" mode=""></image>
						</view>
					</view>
				</view>
			</template>
			<template v-if="queryform.type === 'ENTERPRISE'">
				<view class="form-item">
					<view class="label">公司名称</view>
					<view class="zdy-input">
						<view style="flex: 1;">
							<uv-input v-model="queryform.merchantName" placeholder="请输入公司名称" type="text"
								:border="false" />
						</view>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="form-item">
					<view class="label">商户简称</view>
					<view class="zdy-input">
						<view style="flex: 1;">
							<uv-input v-model="queryform.merchantName" placeholder="请输入名称简称" type="text"
								:border="false" />
						</view>
					</view>
				</view>
			</template>

			<template v-if="queryform.type === 'PERSON'">
				<view class="form-item">
					<view class="label">个人简介</view>
					<view class="textarea">
						<uv-textarea v-model="queryform.intro" border="none" placeholder="请输入介绍"></uv-textarea>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="form-item">
					<view class="label">公司简介</view>
					<view class="textarea">
						<uv-textarea v-model="queryform.intro" border="none" placeholder="请输入介绍"></uv-textarea>
					</view>
				</view>
			</template>

			<view class="form-item">
				<view class="label">城市</view>
				<view class="zdy-input" style="padding: 0 20rpx;" @click="handChooseCity">
					<view style="flex: 1;">
						<text v-if="queryform.city">{{ queryform.city }}</text>
						<text class="place" v-else>请选择</text>
					</view>
					<vew class="arrow">
						<uv-icon name="arrow-right"></uv-icon>
					</vew>
				</view>
			</view>
			<view class="form-item">
				<view class="label">详细地址</view>
				<view class="zdy-input">
					<view style="flex: 1;">
						<uv-input v-model="queryform.address" placeholder="请输入详细地址" type="text" :border="false" />
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="label">联系人</view>
				<view class="zdy-input">
					<view style="flex: 1;">
						<uv-input v-model="queryform.name" placeholder="请输入联系人" type="text" :border="false" />
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="label">联系电话</view>
				<view class="zdy-input">
					<view style="flex: 1;">
						<uv-input type="number" maxlength="11" v-model="queryform.cellphone" placeholder="请输入联系人电话"
							:border="false" />
					</view>
				</view>
			</view>
			<template v-if="queryform.type === 'ENTERPRISE'">
				<view class="form-item">
					<view class="label">社会信用代码</view>
					<view class="zdy-input">
						<view style="flex: 1;">
							<uv-input type="text" disabled v-model="queryform.licenseNo" placeholder="请上传营业执照"
								:border="false" />
						</view>
					</view>
				</view>
			</template>
			<view class="form-item">
				<view class="label">
					<template v-if="queryform.type === 'PERSON'">
						<text>身份证照片</text>
					</template>
					<template v-else>
						<text>法人身份证照片</text>
					</template>
				</view>
				<view class="uplaods">
					<view class="upload" @click="handChooseImg('identityCardFront')">
						<image v-if="queryform.identityCardFront" :src="queryform.identityCardFront" mode="aspectFill">
						</image>
						<image v-else src="../../static/zheng.png" mode=""></image>
						<text>头像面</text>
					</view>
					<view class="upload" @click="handChooseImg('identityCardTail')">
						<image v-if="queryform.identityCardTail" :src="queryform.identityCardTail" mode="aspectFill">
						</image>
						<image v-else src="../../static/fan.png" mode=""></image>
						<text>国徽面</text>
					</view>
				</view>
			</view>
			<template v-if="queryform.type === 'ENTERPRISE'">
				<view class="form-item">
					<view class="label">
						<text>公章</text>
					</view>
					<view class="uplaods">
						<view class="upload-gz" @click="handChooseImg('contractSeal')">
							<image v-if="queryform.contractSeal" :src="queryform.contractSeal" mode="aspectFill">
							</image>
							<image v-else src="../../static/icon/coverupload.png" mode=""></image>
						</view>
					</view>
				</view>
			</template>
			<view class="check">
				<view style="width: 50rpx;">
					<uv-checkbox-group v-model="checkboxValue" shape="circle">
						<uv-checkbox label="" name="ok"></uv-checkbox>
					</uv-checkbox-group>
				</view>

				<view style="flex: 1;" @click="handCheck">
					<text>已阅读并同意</text>
					<text @click.stop="handXy">《入驻协议》</text>
				</view>

			</view>
			<view class="submit">
				<button class="cu-btn" @click="handSubmit">提交</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		toRaw
	} from 'vue'
	import {
		onLoad,
		onPageScroll
	} from "@dcloudio/uni-app";
	import {
		doSubmitAuth,
		doProvince
	} from '@/apis/user.js'
	import uploadFile from '@/utils/ossutil/uploadFile.js'
	import YCubar from '@/components/y-cubar/index.vue'
	import qqMap from '@/utils/qqMap.js'
	import {
		useAppsStore
	} from '@/stores/modules/app.js'
	import {
		storeToRefs
	} from 'pinia'

	const useStore = useAppsStore()
	const {
		getUserInfo: userInfo
	} = storeToRefs(useStore)
	const {
		doUserInfo
	} = (useStore)

	const opacity = ref(0)
	onPageScroll((e) => {
		const childerOpa = Number((e.scrollTop / 200).toFixed(2))
		opacity.value = childerOpa >= 1 ? 1 : childerOpa
	})

	const inactiveStyle = reactive({
		color: '#333333',
		fontSize: '32rpx',
		fontWeight: '550'
	})
	const tabList = reactive([{
		name: '个人认证',
	}, {
		name: '企业认证'
	}])
	let curren = ref(0)
	const tabChange = (e) => {
		curren.value = e.index
		queryform.value.type = e.index === 0 ? 'PERSON' : 'ENTERPRISE'
	}

	const queryform = ref({
		type: 'PERSON',
		merchantName: '',
		intro: '',
		province: '',
		city: '',
		address: '',
		name: '',
		cellphone: '',
		licensePhotos: '',
		identityCardFront: '',
		identityCardTail: ''
	})

	let loading = false
	const handSubmit = async () => {
		if (checkboxValue.value.length === 0) {
			uni.$uv.toast('请先勾选入住协议')
			return
		}
		const params = uni.$uv.deepClone(queryform.value)
		if (!params.merchantName) {
			uni.$uv.toast(params.type === 'PERSON' ? '请输入商户简称' : '请输入公司名称')
			return
		}
		if (!params.intro) {
			uni.$uv.toast(`请输入${params.type === 'PERSON' ? '个人简介' : '公司简介'}`)
			return
		}
		if (!params.city) {
			uni.$uv.toast('请选择城市')
			return
		}
		if (!params.address) {
			uni.$uv.toast('请输入详细地址')
			return
		}
		if (!params.name) {
			uni.$uv.toast('请输入联系人')
			return
		}
		if (!params.cellphone) {
			uni.$uv.toast('请输入联系电话')
			return
		}
		if (params.type === 'ENTERPRISE') {
			if (!params.licensePhotos) {
				uni.$uv.toast('请上传营业执照照片')
				return
			}
		}
		if (!params.identityCardFront) {
			uni.$uv.toast(`请上传身份证正面`)
			return
		}
		if (!params.identityCardTail) {
			uni.$uv.toast(`请上传身份证反面`)
			return
		}
		if (!params.contractSeal) {
			uni.$uv.toast(`请上传公章`)
			return
		}
		if (params.type === 'ENTERPRISE') {
			if (params.type === 'PERSON') {
				params.contractSeal = ''
			}
		}
		if (loading) return
		loading = true
		try {
			await doSubmitAuth(params)
			doUserInfo()
			uni.redirectTo({
				url: `/pagesA/car/success`
			})
		} catch (e) {
			loading = false
		}
	}

	const handChooseCity = () => {
		uni.navigateTo({
			url: '/pagesA/other/city?type=1',
			events: {
				someEvent: async (e) => {
					const data = await doProvince(e.provinceCode)
					queryform.value.province = data.fullname
					queryform.value.city = e.fullname
				}
			}
		})
	}

	const getVerValue = (arr, name) => {
		const info = arr.find(el => el.name === name)
		if (info) {
			return info.value
		}
		return ''
	}

	const handVerify = async (tempFilePaths, src) => {
		uni.showLoading({
			title: '识别中'
		})
		try {
			const base64Url = await getUrlBase64(src)
			uni.uploadFile({
				url: 'https://apis.juhe.cn/businessLicenseOcr/index',
				filePath: tempFilePaths,
				name: 'file',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				formData: {
					key: 'b858ead036f1528eb9f13de091b8ab32',
					detect_direction: 1,
					image: base64Url
				},
				success: (res) => {
					uni.hideLoading()
					if (res.statusCode === 200) {
						const result = JSON.parse(res.data)
						console.log(result)
						if (result.error_code === 0) {
							queryform.value.licenseNo = getVerValue(result.result.res, '社会信用代码')
							queryform.value.name = getVerValue(result.result.res, '法人')
							queryform.value.merchantName = getVerValue(result.result.res, '单位名称')
							queryform.value.address = getVerValue(result.result.res, '地址')
							queryform.value.licensePhotos = src
						} else {
							uni.$uv.toast('图片解析失败')
						}
					} else {
						uni.$uv.toast('图片解析失败')
					}
				},
				fail: (err) => {
					uni.hideLoading()
					uni.$uv.toast('图片解析失败')
				}
			})
		} catch (e) {
			console.log(e)
			uni.$uv.toast('图片解析失败')
			uni.hideLoading()
		}
	}

	const getUrlBase64 = (url) => {
		return new Promise((rel, rej) => {
			uni.request({
				url,
				method: 'GET',
				responseType: 'arraybuffer',
				success: (res) => {
					let base64 = uni.arrayBufferToBase64(res.data)
					rel(base64)
				},
				fail: (err) => {
					rej(err)
				}
			})
		})
	}

	const handChooseImg = (name) => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				uploadFile(res.tempFilePaths[0], 'images/', res.tempFilePaths[0], (src => {
					if (name === 'licensePhotos') {
						handVerify(res.tempFilePaths[0], src)
					} else {
						queryform.value[name] = src
					}
				}), (err => {

				}), (res => {

				}))
			}
		})
	}

	onLoad(() => {
		if (userInfo.value?.merchant?.id) {
			queryform.value = toRaw(userInfo.value).merchant
			if (userInfo.value.merchant.type === 'ENTERPRISE') {
				curren.value = 1
			}
		}
		// uni.getLocation({
		// 	type: 'gcj02',
		// 	isHighAccuracy: true,
		// 	highAccuracyExpireTime: 4000,
		// 	success: async ({
		// 		latitude,
		// 		longitude
		// 	}) => {
		// 		const res = await qqMap.reverseGeocoder(latitude, longitude)
		// 		queryform.value.province = res.result.address_component.province
		// 		queryform.value.city = res.result.address_component.city
		// 	},
		// 	fail: (err) => {
		// 		console.log('错误----', err)
		// 	}
		// })
	})

	const checkboxValue = ref([])
	const handCheck = () => {
		if (checkboxValue.value.length === 1) {
			checkboxValue.value = []
		} else {
			checkboxValue.value = ['ok']
		}
	}
	const handXy = () => {
		uni.navigateTo({
			url: `/pagesA/other/rich?val=rzxy`
		})
	}
</script>

<style lang="scss" scoped>
	.auth-page {
		min-height: 100vh;
		background-color: #F5F5F5;

		&-bg {
			width: 750rpx;
			height: 408rpx;
			background: linear-gradient(180deg, #FFC434 0%, #F5F5F5 100%);
			position: absolute;
			top: 0;
		}

		.hand-top {
			display: flex;
			justify-content: space-between;
			position: relative;
			padding: 18rpx 24rpx 18rpx 40rpx;
			z-index: 2;

			&-left {
				.title {
					margin-top: 40rpx;
					width: 250rpx;
					height: 52rpx;
				}

				.more {
					margin-top: 24rpx;
					font-size: 24rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #666666;
				}
			}

			.bg {
				width: 253.39rpx;
				height: 201.36rpx;
			}
		}

		.form {
			margin-top: -40rpx;
			position: relative;
			z-index: 3;
			background-color: #FFF;
			border-radius: 32rpx 32rpx 0 0;
			padding: 15rpx 32rpx;
			padding-bottom: 80rpx;
			padding-bottom: calc(constant(safe-area-inset-bottom) + 80rpx);
			padding-bottom: calc(env(safe-area-inset-bottom) + 80rpx);

			&-item {
				&:not(:first-child) {
					margin-top: 40rpx;
				}

				.label {
					font-size: 32rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #333333;
				}

				.zdy-input {
					height: 94rpx;
					margin-top: 24rpx;
					background: #F5F5F5;
					border-radius: 16rpx;
					display: flex;
					align-items: center;

					.place {
						font-size: 30rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #999999;
					}
				}

				.uplaods {
					margin-top: 24rpx;
					display: flex;
					align-items: center;

					.upload-gz {
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;

						image {
							width: 180rpx;
							height: 180rpx;
						}
					}

					.upload {
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;

						&:nth-child(2) {
							margin-left: 30rpx;
						}

						image {
							width: 328rpx;
							height: 212rpx;
						}

						text {
							margin-top: 20rpx;
							font-size: 24rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #333333;
						}
					}
				}

				.textarea {
					margin-top: 32rpx;
				}

				.select {
					margin-top: 32rpx;
					height: 94rpx;
					background: #F5F5F5;
					border-radius: 16rpx;
					display: flex;
					align-items: center;
					box-sizing: border-box;
					padding: 0 32rpx;

					&-val {
						flex: 1;

						.place {
							font-size: 30rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #999999;
						}
					}
				}

				.zujin {
					display: flex;
					align-items: center;
					margin-top: 32rpx;

					.zujin-input {
						flex: 1;
						height: 88rpx;
						background: #F5F5F5;
						border-radius: 16rpx;
						display: flex;
						align-items: center;
						padding: 0 38rpx;

						text {
							font-size: 30rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #333333;
						}

						.input {
							margin-left: 10rpx;
							flex: 1;

							input {
								width: 100%;
							}

							.place {
								color: #CCCCCC;
							}
						}
					}

					.line {
						width: 32rpx;
						height: 2rpx;
						background-color: #DDDDDD;
						margin: 0 16rpx;
					}
				}

				.btns {
					margin-top: 32rpx;
					display: flex;
					align-items: center;

					.cu-btn {
						width: 312rpx;
						height: 88rpx;
						background: #F5F5F5;
						border-radius: 16rpx;
						font-size: 30rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #333333;
						border: 1rpx solid #F5F5F5;

						&:last-child {
							margin-left: 62rpx;
						}

						&-active {
							background: #FFF7E4;
							border-color: #FF930D;
							color: #FF930D;
						}
					}
				}
			}

		}

		.check {
			margin-top: 48rpx;
			font-size: 24rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			display: flex;
			align-items: center;

			text {
				color: #999999;

				&:last-child {
					color: #2F6DF4;
				}
			}
		}

		.submit {
			margin-top: 40rpx;

			.cu-btn {
				width: 686rpx;
				height: 100rpx;
				background: #FFC434;
				border-radius: 16rpx;
				font-size: 36rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #333333;
			}
		}
	}
</style>